package grpc.demo;

import com.google.protobuf.ByteString;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.concurrent.TimeUnit;

/**
 * @author Rocket
 * @version 10.0.1
 * @date 2021-09-06 6:16 PM
 */
public class HelloClient {
    
    private final ManagedChannel channel;
    
    private final HelloGrpc.HelloBlockingStub blockingStub;

    private final HelloGrpc.HelloStub stub;


    public HelloClient(String host, int port) {
        channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build();
        blockingStub = HelloGrpc.newBlockingStub(channel);
        stub = HelloGrpc.newStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    public String sayHello(String name, String fileName) throws Exception {
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file);
        ByteString bs = ByteString.readFrom(fis);
        fis.close();
        Demo2.HelloRequest request = Demo2.HelloRequest.newBuilder()
                .setName(name)
                .setPhoto(bs)
                .build();
        Demo2.HelloResponse response = blockingStub.sayHello(request);
        //stub.sayHello();
        return response.getMessage();
    }

    public String updateProtocol(String protocol) {
        Demo2.InstanceRequest req = Demo2.InstanceRequest.newBuilder().setProtocol(protocol).build();
        Demo2.InstanceResponse res = blockingStub.updateProtocol(req);
        return res.getMessage();
    }

    public static void main(String[] args) throws Exception {
        HelloClient client = new HelloClient("localhost", 10051);
        String content = client.sayHello("金鑫", "C:\\Users\\jliu2\\Documents\\Camtasia Studio\\Rec 09-12-21 1.trec");
        System.out.println(content);
        System.out.println(client.updateProtocol("https"));
        client.shutdown();
    }

}
